package com.fm.jbsql.entry;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Vector;
import java.util.Arrays;

import com.fm.jbsql.util.CmdOpt;
import com.fm.jbsql.util.StringComparator;
import com.fm.jbsql.util.JbsqlException;

/**
 * Created by IntelliJ IDEA.
 * User: syaroshenko
 * Date: Jul 13, 2006
 * Time: 11:36:27 AM
 * Class to manage projects: process first level directories or single entries source.
 */

/**
 * Class to manage projects: process first level directories or single entries source. 
 */
final class ProjectManager {
    private static final Logger logger = Logger.getLogger("com.fm.jbsql.entry.ProjectManager");
    private static ProjectManager instance;

    public static ProjectManager getInstance() {
        if ( instance == null ) {
            instance = new ProjectManager();
        }
        return instance;
    }
    /**
     * Constructor.
     */
    private ProjectManager() {
        logger.log(Level.FINE, "start");
        logger.log(Level.FINE, "finish");
    }

    /**
     * Run project.
     * @param cmdopt command line argumetns
     * @throws JbsqlException
     */
    public void run(final CmdOpt cmdopt) throws JbsqlException {
        logger.log(Level.FINE, "start");

        Vector dirs = new Vector();
        Project p;

        if ( cmdopt.isSubdirs() ) {
            Project.findNextFile(cmdopt.getPath(), 1, dirs, false, true, true);
            Object []sdirs = dirs.toArray();
            Arrays.sort(sdirs, new StringComparator());

            for ( int loop = 0; loop < dirs.size(); loop++) {
                cmdopt.setPath(sdirs[loop].toString());
                p = createProject(cmdopt);
                p.run(false);
            }
        }
        else {
            p = createProject(cmdopt);
            p.run(true);
        }

        logger.log(Level.FINE, "finish");
    }

    /**
     * Create Project object based on command line arguments.
     * @param cmdopt command line arguments
     * @return Project
     */
    private static Project createProject(CmdOpt cmdopt) {
        if ( cmdopt.isSqllst() ) return new ProjectSQL(cmdopt);
        else return new ProjectSVN(cmdopt);
    }
}
